﻿using System.Collections;
using System.Collections.Generic;
using Neonagee.LocalPreferences;
using UnityEngine;
using UnityEngine.PlayerLoop;
using UnityEngine.UI;

public class FPSCounterUI : MonoBehaviour
{
    public const string SaveKey = "fpsOpen";
    public Text TxtCount;
    private bool _isFPSOpen = false;
    private float _updateInterval = 0.5f;
    private float _currentFps;
    private int _frames;
    private float _accumulator;
    private float _timeLeft;
    // Start is called before the first frame update

    void Start()
    {
        Reset();
        _timeLeft = _updateInterval;
        _updateFpsConfig();
    }

    // Update is called once per frame
    void Update()
    {
        if (!_isFPSOpen) return;
        _frames++;
        _accumulator += Time.deltaTime;
        _timeLeft -= Time.deltaTime;

        if (_timeLeft <= 0f)
        {
            _currentFps = _accumulator > 0f ? _frames / _accumulator : 0f;
            TxtCount.text = string.Format("{0:N2}", _currentFps);
            _frames = 0;
            _accumulator = 0f;
            _timeLeft += UpdateInterval;
        }
    }

    public float UpdateInterval
    {
        get
        {
            return _updateInterval;
        }
        set
        {
            if (value <= 0f)
            {
                Debug.LogError("Update interval is invalid.");
                return;
            }

            _updateInterval = value;
            Reset();
        }
    }

    public void ShowFPSUI()
    {
        _setFpsShow(2);
    }

    public void HideFPSUI()
    {
        _setFpsShow(1);
    }


    void _setFpsShow(int value)
    {
        if(value != 1 && value != 2) return;
        LocalPrefs.SetInt(SaveKey, value);
        _updateFpsConfig();
    }

    public void Test111()
    {
        Debug.Log("111");
    }

    public float CurrentFps
    {
        get
        {
            return _currentFps;
        }
    }
    
    void _updateFpsConfig()
    {
        _isFPSOpen = false;
        int value = LocalPrefs.GetInt(SaveKey); //0：未赋值 1：关闭 2：开启
        //release包且gm设置开启时打开
        if(!Debug.isDebugBuild)
        {
            if (value == 2) _isFPSOpen = true;
        }else if(value != 1)
        {
            _isFPSOpen = true;
        }
        transform.GetChild(0).gameObject.SetActive(_isFPSOpen);
    }

    private void Reset()
    {
        _currentFps = 0f;
        _frames = 0;
        _accumulator = 0f;
        _timeLeft = 0f;
    }
}
